package com.qianbao.qianbaobusiness.ui.login;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.androidbase.base.mvp.RxMvpPresenter;
import com.androidbase.utils.DeviceUuid;
import com.androidbase.utils.DigestUtils;
import com.androidbase.utils.RxUtils;
import com.baseandroid.config.Constant;
import com.baseandroid.config.Global;
import com.baseandroid.config.MyApi;
import com.baseandroid.retrofit.RxObserver;
import com.baseandroid.retrofit.json.Data;
import com.qianbao.qianbaobusiness.json.ShopListInfo;
import com.qianbao.qianbaobusiness.json.UnPayinfoParentBean;
import com.qianbao.qianbaobusiness.json.UserInfo;
import com.qianbao.qianbaobusiness.json.UserTokenInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class LoginPresent extends RxMvpPresenter<LoginView> {

    MyApi mMyApi;

    @Inject
    public LoginPresent(MyApi myApi) {
        mMyApi = myApi;
    }

    public void requestSmsCode(String phonenum) {
        getView().disableValidateCodeButton();
        Map<String, String> params = new HashMap<>();
        params.put("username", phonenum);
        mMyApi.getSmsCode(params)
                .compose(RxUtils.<Data>applySchedulersLifeCycle(getView()))
                .subscribe(new RxObserver<Data>() {

                    @Override
                    public void onNext(@NonNull Data data) {
                        if (RxObserver.checkJsonCode(data, true)) {
                            countValidateCode();
                        } else {
                            getView().enableValidateCodeButton();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        getView().enableValidateCodeButton();
                    }
                });
    }

    private void countValidateCode() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .compose(RxUtils.<Long>applySchedulersLifeCycle(getView()))
                .subscribe(new RxObserver<Long>() {
                    Disposable disposable;

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long count) {
                        if (count < Constant.VALIDETE_CODE_WATING_TIME_MAX) {
                            getView().countValidateCodeButton(Constant.VALIDETE_CODE_WATING_TIME_MAX - count);
                        } else {
                            if (!disposable.isDisposed()) {
                                disposable.dispose();
                            }
                            getView().resendValidateCodeButton();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        getView().resendValidateCodeButton();
                    }
                });
    }

    public void requestLogin(final String phoneNum, String verifiCode, List<String> phonewhites) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", phoneNum);
        params.put("password", verifiCode);
        if (phonewhites.contains(phoneNum)) {
            params.put("passType", "0");
        } else {
            params.put("passType", "1");
        }

        if (!TextUtils.isEmpty(Global.getPushConfig()) && Global.getPushConfig()
                .equals("1")) {
            params.put("audienceChannel", "1");
            params.put("audience", PushServiceFactory.getCloudPushService()
                    .getDeviceId());
        } else {
            params.put("audienceChannel", "0");
            params.put("audience", DigestUtils.md5Hex(phoneNum + DeviceUuid.getDeviceId(Global
                    .getContext())));
        }

        mMyApi.requestLogin(params)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        getView().showLoadingDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Data<UserTokenInfo>>() {
                    @Override
                    public void accept(@NonNull Data<UserTokenInfo> userTokenInfoData) throws
                            Exception {
                        if (RxObserver.checkJsonCode(userTokenInfoData, true)) {
                            Global.setUserTokenInfo(userTokenInfoData.getResult());
                        }
                    }
                })
                .observeOn(Schedulers.newThread())
                .flatMap(new Function<Data<UserTokenInfo>, Observable<Data<UserInfo>>>() {
                    @Override
                    public Observable<Data<UserInfo>> apply(@NonNull Data<UserTokenInfo> userTokenInfoData) throws
                            Exception {
                        if (RxObserver.checkJsonCode(userTokenInfoData, false)) {
                            return mMyApi.getUserinfo();
                        }

                        return null;
                    }
                })
                .flatMap(new Function<Data<UserInfo>, Observable<Data<ShopListInfo>>>() {
                    @Override
                    public Observable<Data<ShopListInfo>> apply(Data<UserInfo> userInfoBeanData) throws
                            Exception {
                        if (RxObserver.checkJsonCode(userInfoBeanData, false)) {
                            Global.setUserInfoBean(userInfoBeanData.getResult());
                            Global.setUsrePhotoNumber(phoneNum);
                            return mMyApi.getUserShopListInfo();
                        }

                        return null;
                    }
                })
                .compose(RxUtils.<Data<ShopListInfo>>applySchedulersLifeCycle(getView()))
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        getView().closeLoadingDialog();
                    }
                })
                .subscribe(new RxObserver<Data<ShopListInfo>>() {

                    @Override
                    public void onNext(@NonNull Data<ShopListInfo> shopListInfoData) {
                        if (RxObserver.checkJsonCode(shopListInfoData, true)) {
                            Global.setShopListInfo(shopListInfoData.getResult());
                            getView().OnLoginInfo(true);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        getView().OnLoginInfo(false);
                    }

                });
    }
}
